<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="预警条件" prop="configId">
        <el-select
          v-model="queryParams.configId"
          placeholder="请选择预警条件"
          clearable
          class="!w-240px"
          @change="handleQuery"
        >
          <el-option
            v-for="config in configOptions"
            :key="config.id"
            :label="config.name"
            :value="config.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="证件号码" prop="idNumber">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入身份证号/护照号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column
        label="人员姓名"
        align="center"
        prop="personName"
        width="150px"
      >
        <template #default="scope">
          <el-tooltip :content="scope.row.idNumber || '无证件号'" placement="top">
            <el-button link type="primary" @click="openDetail(scope.row.personId)">
              {{ scope.row.personName }}
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="触网时间"
        align="center"
        prop="warningTime"
        :formatter="dateFormatter"
        width="190px"
      />
      <el-table-column label="预警内容" align="left" prop="warningContent" min-width="450px"/>
      <el-table-column
        label="状态"
        align="left"
        prop="isRead"
        width="160px"
      >
        <template #header>
          <div style="display: flex; align-items: center; justify-content: center;">
            <span>状态</span>
            <el-button
              type="text"
              size="small"
              style="margin-left: 30px; color: #409EFF;"
              @click="handleMarkAllRead"
              :disabled="!list.length"
            >
              全选
            </el-button>
          </div>
        </template>
        <template #default="scope">
          <!-- 核心：用一个 inline-flex 容器包裹所有元素，实现一行排列 + 垂直居中 -->
          <div style="display: inline-flex; align-items: center;">
            <!-- 未读状态：图标+文字 -->
            <template v-if="scope.row.isRead === 0">
              <el-icon color="#F56C6C" size="18">
                <Message/>
              </el-icon>
              <span style="margin-left: 6px; color: #F56C6C;">未读</span>
            </template>

            <!-- 已读状态：图标+文字 -->
            <template v-else-if="scope.row.isRead === 1">
              <el-icon color="#67C23A" size="18">
                <Check/>
              </el-icon>
              <span style="margin-left: 6px; color: #67C23A;">已读</span>
            </template>

            <!-- 阅读按钮：仅未读显示，与状态在同一行 -->
            <el-button
              v-if="scope.row.isRead === 0"
              type="text"
              size="small"
              style="margin-left: 12px; color: #409EFF;"
              @click="handleMarkSingleRead(scope.row)"
            >
              阅读
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {dateFormatter} from '@/utils/formatTime'
import { WarningIndividualApi, WarningIndividualVO } from '@/api/member/warningindividual'
import Pagination from '@/components/Pagination/index.vue'
import { ElMessage } from 'element-plus'
import {Check, Message} from "@element-plus/icons-vue";
import {WarnConfigListVo, WarnConfigRespVO, WarningGatherApi} from "@/api/member/warninggather";

// 定义组件名称
defineOptions({ name: 'WarningInOutHzIndex' })

// ======================== 列表相关逻辑 ========================
const loading = ref(true)
const configLoading = ref(false)
const list = ref<WarningIndividualVO[]>([])
const total = ref(0)
// 预警配置下拉框选项
const configOptions = ref<WarnConfigRespVO[]>([])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  warnType: 3,
  personId: undefined,
  configId: undefined,
  idNumber: undefined
})

// 1. 单条标记为已读
const handleMarkSingleRead = async (row) => {
  try {
    // 调用后端接口：标记该条记录为已读（传入row.id等关键参数）
    await WarningIndividualApi.markSingleRead(row.id)

    // 前端临时更新状态（接口成功后）
    row.isRead = 1
    ElMessage.success('标记已读成功')
  } catch (error) {
    // 先判断error是否为Error类型
    const errorMsg = error instanceof Error ? error.message : '网络异常'
    ElMessage.error('标记已读失败：' + errorMsg)
  }
}

// 2. 全部标记为已读
const handleMarkAllRead = async () => {
  const unreadRows = list.value.filter(row => row.isRead === 0)
  if (!unreadRows.length) {
    ElMessage.info('已无未读记录')
    return
  }

  try {
    // 1. 提取未读记录的id列表
    const unreadIds = unreadRows.map(row => row.id)

    // 2. 调用批量接口（关键修正：使用markBatchRead而非markSingleRead）
    await WarningIndividualApi.markBatchRead(unreadIds)

    // 3. 前端更新状态
    unreadRows.forEach(row => {
      row.isRead = 1
    })
    ElMessage.success(`成功标记${unreadIds.length}条记录为已读`)
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '批量标记已读失败'
    ElMessage.error(errorMsg)
  }
}

const queryFormRef = ref<InstanceType<any> | null>(null)

// 路由相关
const { push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'MemberUserDetail', params: { id } })
}

/** 获取预警配置下拉框数据 */
const getConfigOptions = async () => {
  configLoading.value = true
  try {
    // 查询聚集预警类型的配置（warnType=2）
    const params: WarnConfigListVo = {
      warnType: 3
    }
    const data = await WarningGatherApi.getConfigSelect(params)
    configOptions.value = data || []
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '网络异常'
    ElMessage.error('获取预警配置失败：' + errorMsg)
    console.error('获取预警配置失败:', error)
  } finally {
    configLoading.value = false
  }
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const data = await WarningIndividualApi.getWarningIndividualPage(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取预警列表失败')
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// ======================== 生命周期 ========================
onMounted(() => {
  // 先加载配置下拉框，再加载列表数据
  getConfigOptions().then(() => {
    getList()
  })
})
</script>

<style scoped>
/* 分页样式 */
:deep(.el-pagination) {
  margin-top: 15px;
  text-align: right;
}
</style>
